﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using UFIDA.U9.Cust.XH.PlugBE.Model;
using UFIDA.U9.Cust.XH.PlugBE.Tool;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;

namespace UFIDA.U9.Cust.XH.PlugBE
{
    /// <summary>
    /// 请购单
    ///  采购申请、 委外申请 业务类型区分
    /// </summary>
    class PurchaseRequestSubmitExtend : IEventSubscriber
    {
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体													 

            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
                return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
                return;
            UFIDA.U9.PR.PurchaseRequest.PR entity = key.GetEntity() as UFIDA.U9.PR.PurchaseRequest.PR;
            if (entity == null)
                return;
            //请购单审核提交事件
            if (PubWebClass.IsSyncToOA() && entity.BusinessDate > PubWebClass.startSysDate && entity.OriginalData.Status == PR.PurchaseRequest.PRStatusEnum.OpenOpen && entity.Status == UFIDA.U9.PR.PurchaseRequest.PRStatusEnum.Approving)
            {
                string strbilltype = "采购申请";
                string oatablename = "formtable_main_19_dt1";
                string biztype = "";
                foreach (PR.PurchaseRequest.PRLine item in entity.PRLineList)
                {
                    biztype = UFIDA.U9.Base.Doc.BusinessTypeEnum.EnumRes.GetResource(item.BizType.Name);
                    break;
                }
                if (biztype.Contains("委外"))
                {
                    strbilltype = "委外申请";
                    oatablename = "formtable_main_50_dt1";
                }
                Tool.OAFlowParam OA = new Tool.OAFlowParam();
                //根据不同的组织和单据获取ID信息
                OA.workflowId = Tool.DBHelper.getOAFlowID(entity.Org.Code, strbilltype);
                OA.requestName = strbilltype;
                DataTable dt = Tool.DBHelper.getU9Datatble($" exec proc_getDatabaseTable '{entity.Org.ID}','{entity.ID}','{strbilltype}' ");
                if (dt == null)
                {
                    return;
                }
                string userId = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //创建人编码
                    string createcode = dt.Rows[i]["createcode"].ToString();
                    userId = PubWebClass.GetOAUserIDByCode(createcode);
                    //人员
                    string rycode = dt.Rows[i]["xqry"].ToString();
                    dt.Rows[i]["xqry"] = PubWebClass.GetOAUserIDByCode(rycode);
                    //部门
                    string depcode = dt.Rows[i]["xqbm"].ToString();
                    dt.Rows[i]["xqbm"] = PubWebClass.GetOADepIDByCode(depcode);
                    //组织
                    string orgcode = dt.Rows[i]["hszz"].ToString();
                    dt.Rows[i]["hszz"] = PubWebClass.GetOAOrgIDByCode(orgcode);
                }
                OA.mainData = Tool.DBHelper.getMainDtTONVList(dt, entity.ID.ToString());
                DataTable dtc = DBHelper.getU9Datatble($" exec proc_getDatabaseTable '{entity.Org.ID}','{entity.ID}','{strbilltype}行' ");

                if (string.IsNullOrEmpty(dt.Rows[0]["id"].ToString()))
                {
                    OA.detailData = Tool.DBHelper.getChildDtTONVList(dtc, oatablename);
                }
                else
                {
                    OA.detailData = Tool.DBHelper.getChildDtTONVList(dtc, oatablename, "1");
                }
                string main = JsonConvert.SerializeObject(OA.mainData);
                string detial = JsonConvert.SerializeObject(OA.detailData);
                //  每次提交即新建流程  更新提交流程不能用
                if (dt.Rows.Count > 0 && string.IsNullOrEmpty(dt.Rows[0]["id"].ToString()))
                {                                      
                    string data = $"workflowId={ OA.workflowId}&requestName={OA.requestName }&mainData={ HttpUtility.UrlEncode(main)}&detailData={ HttpUtility.UrlEncode(detial)}";           
                    OARequestResult oARequestResult = PubWebClass.doCreateRequest(data, userId, strbilltype, $"【{strbilltype}】{main}\r\n\r\n {detial}");
                    if (oARequestResult.code.ToLower().Contains("success"))
                    {
                        //回写流程号到U9
                        string sql = $"update PR_PR set DescFlexField_PrivateDescSeg1='{oARequestResult.data.requestid}' where id={entity.ID} ";
                        DataSet ds = new DataSet();
                        int result = UFSoft.UBF.Util.DataAccess.DataAccessor.RunSQL(UFSoft.UBF.Util.DataAccess.DataAccessor.GetConn(), sql, null, null, true, out ds);
                    }
                }
                else
                {
                    string id = dt.Rows[0]["id"].ToString();
                    //OA更新接口                    
                    string data = $"otherParams=save&requestId={id}&requestName={OA.requestName }&mainData={ HttpUtility.UrlEncode(main)}&detailData={ HttpUtility.UrlEncode(detial)}";
                    OARequestResult oARequestResult = PubWebClass.submitRequest(data, userId, strbilltype, $"【{strbilltype}】{main}\r\n\r\n {detial}");

                }

                #endregion
            }

        }
    }
}
